package com.suncky.frame.account;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.suncky.frame.AppConfig;
import com.suncky.frame.utils.GsonUtils;

import java.lang.reflect.ParameterizedType;

public class PreferenceAccountStorage<T> implements AccountStorage<T> {
    private final SharedPreferences sharedPreferences;
    private final Class<T> tClass;

    public PreferenceAccountStorage(Class<T> tClass) {
        sharedPreferences = AppConfig.getAppContext().getSharedPreferences(ACCOUNT_PREFERENCE_NAME, Context.MODE_PRIVATE);
        this.tClass = tClass;
    }

    @Override
    public void saveAccount(T account) {
        sharedPreferences.edit().putString(SP_KEY_ACCOUNT_DATA, GsonUtils.objectToJson(account)).apply();
    }

    @Override
    public void removeAccount() {
        sharedPreferences.edit().remove(SP_KEY_ACCOUNT_DATA).apply();
    }

    @Override
    public T getAccount() {
        String account = sharedPreferences.getString(SP_KEY_ACCOUNT_DATA, "");
        if (TextUtils.isEmpty(account)) {
            return null;
        }
        try {
            return GsonUtils.jsonToObject(tClass, account);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void saveToken(String token) {
        sharedPreferences.edit().putString(SP_KEY_ACCOUNT_TOKEN, token).apply();
    }

    @Override
    public String getToken() {
        return sharedPreferences.getString(SP_KEY_ACCOUNT_TOKEN, "");
    }

    @Override
    public void removeToken() {
        sharedPreferences.edit().remove(SP_KEY_ACCOUNT_TOKEN).apply();
    }

}
